import AMapLoader from '@amap/amap-jsapi-loader';
import { onMounted, onUnmounted, ref } from 'vue';

export const useAMap = (id: string, aMapCallback?: (aMapContext: any) => void): any => {
  const map = ref<any>();
  onMounted(() => {
    // @ts-ignore
    window._AMapSecurityConfig = {
      securityJsCode: process.env.VUE_APP_MAP_APP_KEY,
    };

    AMapLoader.load({
      key: process.env.VUE_APP_MAP_SECRET_KEY || '',
      version: '2.0',
      plugins: ['AMap.Scale'],
    })
      .then(AMap => {
        map.value = new AMap.Map(id, {
          viewMode: '2D',
          zoom: 13,
          features: ['bg', 'road', 'building', 'point'],
        });
        const placeSearch = ref();
        const mouseTool = ref();
        AMap.plugin(['AMap.PlaceSearch', 'AMap.MouseTool'], () => {
          placeSearch.value = new AMap.PlaceSearch({
            map: map.value,
          });
          mouseTool.value = new AMap.MouseTool(map.value);
        });

        if (typeof aMapCallback === 'function') {
          aMapCallback({
            AMap,
            Map: map.value,
            PlaceSearch: placeSearch.value,
            MouseTool: mouseTool.value,
          });
        }
      })
      .catch(e => {
        console.log('初始化地图时出错!', e);
      });
  });

  onUnmounted(() => {
    if (map.value) {
      map.value.destroy();
    }
  });
};
